package com.framework.web.restful.util;

import com.framework.web.restful.doamin.AlarmAppServiceRequestInfo;
import com.framework.web.restful.doamin.CAError;
import com.framework.web.restful.doamin.CommonResponseErrorResult;
import com.framework.web.restful.doamin.MethodMappingBean;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class RestfulUtil {

	/**
	 * 通用的返回错误对象
	 * @param id
	 * @param caError
	 * @return
	 */
	public static CommonResponseErrorResult setCommonErrorRusltObj(int id, CAError caError) {
		CommonResponseErrorResult commonResponseErrorResult = new CommonResponseErrorResult();
		commonResponseErrorResult.setError(caError);
		commonResponseErrorResult.setId(id);
		return commonResponseErrorResult;
	}


	/**
	 * 获取客户端IP地址
	 *
	 * @param request
	 * @return 客户端IP地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取MethodMapping
	 * @return
	 */
	public static CaseInsensitiveMap getMethodMapping(int div) {
		CaseInsensitiveMap ret = null;
		RestfulMethodMappingReader reader = new RestfulMethodMappingReader();
		MethodMappingBean bean = reader.read(div);
		if (bean != null && bean.getMethodNamesMap() != null) {
			ret = bean.createCaseInsensitiveMap();
		}
		return ret;
	}


	/**
	 * 检查请求JSON-RPC规范
	 * @param requestInfo
	 * @return
	 */
	public static boolean checkJsonRpcFormat (AlarmAppServiceRequestInfo requestInfo) {
		boolean ret = true;
		//jsonrpc : 2.0
		if (!"2.0".equals(requestInfo.getJsonrpc())) {
			ret = false;
		}
		//method is not null
		if (StringUtils.isEmpty(requestInfo.getMethod())) {
			ret = false;
		}
		return ret;
	}

	/**
	 * 检查请求JSON-RPC规范
	 * @param requestInfo
	 * @return
	 *//*
	public static boolean checkJsonRpcFormat (OutSideApiRequestInfo<?> requestInfo) {
		boolean ret = true;
		//jsonrpc : 2.0
		if (!"2.0".equals(requestInfo.getJsonrpc())) {
			ret = false;
		}
		//method is not null
		if (StringUtils.isEmpty(requestInfo.getMethod())) {
			ret = false;
		}
		return ret;
	}*/
}
